<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use App\Constants\ErrorCode;
use App\Exception\BussinessException;
use App\Request\UploadRequest;
use App\Utils\Qiniu;
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\Utils\Str;
use League\Flysystem\Filesystem;

class Upload extends AbstractController
{
    public function index(Filesystem $filesystem)
    {
        $filesystem->write('txt/20200404/file.txt', 'contents1112121');
    }

    /**
     * 七牛云上传文件.
     * @throws \League\Flysystem\FilesystemException
     */
    public function qiniuUpload(UploadRequest $uploadRequest, FilesystemFactory $filesystemFactory): array
    {
        $qiniu = $filesystemFactory->get('qiniu');
        $file = $uploadRequest->file('file');
        if ($file->isValid()) {
            throw new BussinessException(ErrorCode::UPLOAD_ERROE, '');
        }
        $extension = strtolower($file->getExtension()) ?: 'png';
        $filename = time() . '_' . Str::random(10) . '.' . $extension;
        $qiniu->write($filename, file_get_contents($file->getRealPath()));
        $url = Qiniu::getDownLoadurl($filename);
        return [
            'filename' => $filename,
            'url' => $url,
        ];
    }
}
